/*
 * Created on 2005/4/12
 *
 */
package com.erp.app.report.genericInquiry;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.erp.app.common.ProjectConstants;
import com.erp.app.report.genericInquiry.inquiryCriteria.beans.vo.InquiryCriteriaVO;
import com.erp.app.report.genericInquiry.inquiryDisplay.beans.vo.InquiryDisplayVO;
import com.erp.app.report.genericInquiry.inquiryMaster.beans.GenericInquiryMasterDelegate;
import com.erp.app.report.genericInquiry.inquiryMaster.beans.GenericInquiryMasterVO;
import com.erp.app.report.genericInquiry.inquiryMaster.dao.GenericInquirySearchCriteria;
import com.erp.app.report.genericInquiry.inquiryMaster.ejb.GenericInquiryMasterPK;
import com.erp.app.report.genericInquiry.inquiryOutput.beans.vo.InquiryOutputVO;
import com.erp.app.report.genericInquiry.inquirySp.beans.vo.InquirySpVO;
import com.erp.app.util.popupSearchTemplate.InvalidComponentArgumentException;
import com.erp.app.util.popupSearchTemplate.PopupSearchTemplateComponent;
import com.erp.app.util.popupSearchTemplate.PopupSearchTemplateFactory;
import com.erp.app.util.web.WebUtil;
import com.erp.common.web.SearchResultRow;
import com.erp.framework.SimpleConstants;
import com.erp.framework.controller.action.SimpleSearchStyleAction;
import com.erp.framework.exceptions.FindRecordException;
import com.erp.framework.model.delegate.SimpleSearchMaintStyleDelegate;
import com.erp.framework.model.pk.SimpleBasePk;
import com.erp.framework.model.vo.ChildList;
import com.erp.framework.model.vo.SimpleBaseVo;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.user.User;

public class GenericInquirySearchAction extends SimpleSearchStyleAction {
	private static final String ACTION_RETURN = "return";
	private static final String ACTION_POPUP_SEARCH = "popupSearch";
	private static final String ACTION_CLEAR_POPUP = "clearPopup";
	private static final String ACTION_CREATE_EXCEL = "createReport";
	private static final String ACTION_CREATE_PDF = "printPdf";
	private static final String ACTION_CREATE_TXT = "createTxt";
	private static final String ACTION_CREATE_HTML_TXT = "createHtmlTxt";
	private static final String ACTION_CREATE_EXCEL_HTML = "createHtmXls";
	private static final String ACTION_CREATE_CSV = "createCsv";
	private static final String ACTION_CREATE_EXCEL_WITH_JAVA = "createExcelWithJava";
	private static final String ACTION_CREATE_CSV_WITH_JAVA = "createCsvWithJava";
	private static final String ACTION_CREATE_EXCEL_HTML_WITH_JAVA = "createHtmXlsWithJava";
	private static final String ACTION_DROPDOWN_OC = "dropdownOC";
	private static final String STATUS_POPUP_SEARCH = ACTION_POPUP_SEARCH;
	private static final String STATUS_CREATE_EXCEL = ACTION_CREATE_EXCEL;
	private static final String STATUS_CREATE_PDF = ACTION_CREATE_PDF;
	private static final String STATUS_CREATE_TXT = ACTION_CREATE_TXT;
	private static final String STATUS_CREATE_HTML_TXT = ACTION_CREATE_HTML_TXT;
	private static final String STATUS_CREATE_EXCEL_HTML = ACTION_CREATE_EXCEL_HTML;
	private static final String STATUS_CREATE_CSV = ACTION_CREATE_CSV;
	private static final String STATUS_CREATE_EXCEL_WITH_JAVA = ACTION_CREATE_EXCEL_WITH_JAVA;
	private static final String STATUS_CREATE_CSV_WITH_JAVA = ACTION_CREATE_CSV_WITH_JAVA;
	private static final String STATUS_CREATE_EXCEL_HTML_WITH_JAVA = ACTION_CREATE_EXCEL_HTML_WITH_JAVA;

    //to be implement when needed
    protected void setFormType(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors){}
    
    
	protected String getFunctionId() {
		return "genericInquiry.do";
	}

	protected String getMasterFormSessionName() {
		return "genericInquirySearchForm";
	}

	protected String getSessionMasterDelegate() {
		return "GENERIC_INQUIRY_MASTER_DELEGATE";
	}

	protected Class getMasterDelegateClass() {
		return GenericInquiryMasterDelegate.class;
	}

	protected Class getMasterFormClass() {
		return GenericInquirySearchForm.class;
	}

	protected Class getMasterVOClass(ActionForm form) {
		return getMasterVOClass();
	}

	protected Class getMasterVOClass() {
		return InquiryOutputVO.class;
	}

	protected Class getSearchCriteriaClass() {
		return GenericInquirySearchCriteria.class;
	}

	protected String getModuleName(ActionMapping mapping, ActionForm formIn,
			HttpServletRequest request, HttpServletResponse response) {
		GenericInquirySearchForm form = (GenericInquirySearchForm) formIn;
		String inquiryType = form.getInquiryType() == null ? (String) request.getParameter(GenericInquiryConstants.REQUEST_KEY_INQUIRY_TYPE) : form.getInquiryType();
		return inquiryType;
	}

	protected boolean getLoadOnEnter() {
		return false;
	}

	protected boolean getResetOnEnter() {
		return false;
	}

	protected SimpleSearchMaintStyleDelegate getMasterDelegate(HttpSession session) {

		try {
			if (session.getAttribute(getSessionMasterDelegate()) != null) {
				return (SimpleSearchMaintStyleDelegate) session.getAttribute(getSessionMasterDelegate());
			} else {
				SimpleSearchMaintStyleDelegate dg = (SimpleSearchMaintStyleDelegate) getMasterDelegateClass().newInstance();
				session.setAttribute(getSessionMasterDelegate(), dg);
				return dg;
			}
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
		return null;
	}

    protected SimpleBasePk getPk(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors){
        
        String inqType = request.getParameter(GenericInquiryConstants.REQUEST_KEY_INQUIRY_TYPE);
        HttpSession session = request.getSession(false);
        String companyCode = WebUtil.getAppropriateCompanyCode(session, null);
        Locale locale = getLocale(request);        
        String langCode = (String)session.getAttribute(ProjectConstants.SESSION_SYSTEM_LANG);
        
        //return new GenericInquiryMasterPK(companyCode, inqType, null, locale.getDisplayName());
        return new GenericInquiryMasterPK(companyCode, inqType, null, langCode);
    }
    
	protected void initPage(ActionMapping mapping, ActionForm formIn,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors) {
		Logger.info("[Generic Inquiry] - Init");
		
		GenericInquiryMasterDelegate delegate = new GenericInquiryMasterDelegate();
		GenericInquirySearchForm form = (GenericInquirySearchForm) formIn;
		HttpSession session = request.getSession(false);
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);
		String type = request.getParameter(GenericInquiryConstants.REQUEST_KEY_INQUIRY_TYPE);
		
		String langCode = (String)session.getAttribute(ProjectConstants.SESSION_SYSTEM_LANG);

		super.initPage(mapping, formIn, request, response, errors);

		if (CommonUtil.isEmpty(type)) {
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.genericInquiry.typeUnspecified"));
			super.processActionClear(mapping, formIn, request, response, errors);
			if (form.getGenericInquiryMasterVO() != null)
				form.getGenericInquiryMasterVO().removeChilds(InquiryCriteriaVO.class);
			return;
		}

		form.setInquiryType(type);

		try {			
            String companyCode = WebUtil.getAppropriateCompanyCode(session, null);
			Locale locale = getLocale(request);
			
			//GenericInquiryMasterVO vo = delegate.initialize(form.getInquiryType(), editingUser.getUserId(), locale.getDisplayName());
			GenericInquiryMasterVO vo = delegate.initialize(form.getInquiryType(), editingUser.getUserId(), langCode);
			vo.setCompanyCode(companyCode);

			if (vo.getLocalChilds(InquirySpVO.class).size() == 0) {
				errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.generalInquiry.unknownType"));
				super.processActionClear(mapping, formIn, request, response, errors);
				
				if (form.getGenericInquiryMasterVO() != null)
					form.getGenericInquiryMasterVO().removeChilds(InquiryCriteriaVO.class);
				
				return;
			}

			form.setGenericInquiryMasterVO(vo);
			Collection list = getDefaultValuesCollection(session, form);
			Collection defaultValuesList = delegate.getDefaultCriteriaValues(list, editingUser.getUserId());
			form.setDefaultValues(defaultValuesList);

		} catch (FindRecordException e) {
			Logger.logExceptions(this, e);
		} catch (RemoteException e) {
			Logger.logExceptions(this, e);
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	private Collection getDefaultValuesCollection(HttpSession session,
			GenericInquirySearchForm form) {
		Collection masterList = new ArrayList();
        Collection fromList = new ArrayList();
        Collection toList = new ArrayList();
        
        masterList.add(fromList);
        masterList.add(toList);
        
        GenericInquiryMasterVO vo = form.getGenericInquiryMasterVO();
        Collection critList = vo.getLocalChilds(InquiryCriteriaVO.class);
        InquiryCriteriaVO critVO = null;
        
        int counter = 0;
        for (Iterator it = critList.iterator(); it.hasNext();) {
            critVO = (InquiryCriteriaVO)it.next();
            
            fromList.add(GenericInquiryUtil.parseQueryString(form, session, critVO.getDefaultValueFm(), counter));
            toList.add(GenericInquiryUtil.parseQueryString(form, session, critVO.getDefaultValueTo(), counter));
            counter++;
        }
        
        return masterList;
	}

	protected ActionForward handlePageEvent(ActionMapping mapping,
			ActionForm formIn, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {

		ActionForward actionForward = new ActionForward(mapping.getInput());
		GenericInquirySearchForm form = (GenericInquirySearchForm) formIn;
		String action = CommonUtil.nullToString(form.getPageEvent());
		
		preprocess(form);

		if (!isHandled(request) && action.equalsIgnoreCase(ACTION_POPUP_SEARCH)) {
			setHandled(request);
			processActionPopupSearch(form, request, response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CLEAR_POPUP)) {
			setHandled(request);
			processActionClearPopup(mapping, form, request, response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_EXCEL)) {
			setHandled(request);
			actionForward = processActionCreateExcel(mapping, form, request,
					response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_PDF)) {
			setHandled(request);
			actionForward = prcoessActionPrintPdf(mapping, form, request,
					response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_TXT)) {
			setHandled(request);
			actionForward = processActionCreateTxt(mapping, form, request,
					response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_HTML_TXT)) {
			setHandled(request);
			actionForward = processActionCreateHtmlTxt(mapping, form, request,
					response, errors);			
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_EXCEL_HTML)) {
			setHandled(request);
			actionForward = processActionCreateExcelHtml(mapping, form,
					request, response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_CSV)) {
			setHandled(request);
			actionForward = processActionCreateCsv(mapping, form, request,
					response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_EXCEL_WITH_JAVA)) {
			setHandled(request);
			actionForward = processActionCreateExcelWithJava(mapping, form,
					request, response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_EXCEL_HTML_WITH_JAVA)) {
			setHandled(request);
			actionForward = processActionCreateExcelHtmlWithJava(mapping, form,
					request, response, errors);
		} else if (!isHandled(request)
				&& action.equalsIgnoreCase(ACTION_CREATE_CSV_WITH_JAVA)) {
			setHandled(request);
			actionForward = processActionCreateCsvWithJava(mapping, form,
					request, response, errors);
		} else if (!isHandled(request) && ACTION_RETURN.equals(action)) {
			actionForward = processActionReturn(mapping, form, request, response, errors);
		} else if (!isHandled(request) && action.equalsIgnoreCase(ACTION_DROPDOWN_OC)) {
			actionForward = new ActionForward(mapping.getInput());
		} else { // all other actions will be delegated to the url provided by the t_inquiry_sp.maint_url column
			actionForward = processActionDelegate(mapping, form, request, response, errors);
		}

		return actionForward;
	}
	
	protected ActionForward processActionDelegate(
			ActionMapping mapping,
			ActionForm formIn,
			HttpServletRequest request,
			HttpServletResponse response,
			ActionErrors errors) {
		GenericInquirySearchForm form = (GenericInquirySearchForm)formIn;
		
		GenericInquiryMasterVO vo = form.getGenericInquiryMasterVO();
		
		if (vo == null)
			return new ActionForward(mapping.getInput());
		
		List sp_list = form.getGenericInquiryMasterVO().getLocalChilds(InquirySpVO.class);
		
		ActionForward actionForward = new ActionForward(mapping.getInput());
		
		if (sp_list.size() > 0) {
			InquirySpVO inquirySpVO = (InquirySpVO)sp_list.get(0);
			request.setAttribute("pageEvent", form.getPageEvent());
			actionForward = new ActionForward(inquirySpVO.getMaintURL());
		} else {
			Logger.info("Failed to delegate action.  Reason: sp info is missing.");
		}
		
		return actionForward;
	}
	
	protected ActionForward processActionCreate(ActionMapping mapping,
			 ActionForm formIn,
			 HttpServletRequest request,
			 HttpServletResponse response,
			 ActionErrors errors) {
		GenericInquirySearchForm form = (GenericInquirySearchForm)formIn;
		
		GenericInquiryMasterVO vo = form.getGenericInquiryMasterVO();
		
		if (vo == null)
			return new ActionForward(mapping.getInput());
		
		List sp_list = form.getGenericInquiryMasterVO().getLocalChilds(InquirySpVO.class);
		
		ActionForward actionForward = null;
		
		if (sp_list.size() > 0) {
			InquirySpVO inquirySpVO = (InquirySpVO)sp_list.get(0);
			request.setAttribute("pageEvent", form.getPageEvent());
			actionForward = new ActionForward(inquirySpVO.getMaintURL());
		} else
			actionForward = new ActionForward(mapping.getInput());		
		
		return actionForward;
	}	
	
	public ActionForward processActionReturn(
			ActionMapping mapping, 
			GenericInquirySearchForm form, 
			HttpServletRequest request,
			HttpServletResponse response,
			ActionErrors errors) {
		ActionForward actionForward = new ActionForward(mapping.getInput());
		
		return actionForward;
	}
	

	public ActionForward processActionCreateExcelHtmlWithJava(
			ActionMapping mapping, GenericInquirySearchForm form,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors) {
		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_TXT);
		HttpSession session = request.getSession(false);
		if (errors.size() > 0) {
			return actionForward;
		}

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_EXCEL_HTML_WITH_JAVA);
		return actionForward;
	}

	public ActionForward processActionCreateExcelWithJava(
			ActionMapping mapping, GenericInquirySearchForm form,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors) {

		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_EXCEL);
		HttpSession session = request.getSession(false);

		if (errors.size() > 0) {
			return actionForward;
		}

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_EXCEL_WITH_JAVA);
		return actionForward;
	}

	public ActionForward processActionCreateCsv(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_TXT);
		HttpSession session = request.getSession(false);

		if (errors.size() > 0)
			return actionForward;

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_CSV);
		return actionForward;
	}

	public ActionForward processActionCreateCsvWithJava(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_TXT);
		HttpSession session = request.getSession(false);
		if (errors.size() > 0) {
			return actionForward;
		}

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_CSV_WITH_JAVA);
		return actionForward;
	}

	private ActionForward processStatusCreateExcelHtml(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) throws Exception {
		GenericExcelHtmlGenerator htmlGenerator = new GenericExcelHtmlGenerator(
				form);
		htmlGenerator.generate(mapping, request, response, servlet, errors);

		return null;
	}

	public ActionForward processActionCreateExcelHtml(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_EXCEL);

		HttpSession session = request.getSession(false);
		if (errors.size() > 0)
			return actionForward;

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_EXCEL_HTML);
		return actionForward;
	}

	public ActionForward processActionClearPopup(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = new ActionForward(mapping.getInput());
		int idx = Integer.parseInt(form.getPageEventSrc());

		form.setSrchFrom(idx, "");
		form.setSrchFromLabel(idx, "");

		return actionForward;
	}
	
	public ActionForward processActionCreateTxt(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_TXT);
		HttpSession session = request.getSession(false);
		if (errors.size() > 0)
			return actionForward;

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_TXT);
		return actionForward;
	}

	public ActionForward processActionCreateHtmlTxt(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_HTML_TXT);
		HttpSession session = request.getSession(false);
		if (errors.size() > 0)
			return actionForward;

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_HTML_TXT);
		form.validateRowCount(form);
		return actionForward;
	}
	
	public ActionForward prcoessActionPrintPdf(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_PDF);
		HttpSession session = request.getSession(false);
		if (errors.size() > 0) {
			return actionForward;
		}

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_PDF);
		return actionForward;
	}

	private ActionForward processActionCreateExcel(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = processActionSearch(mapping, form,
				request, response, errors,
				ProjectConstants.GENERIC_REPORT_TYPE_EXCEL);
		HttpSession session = request.getSession(false);
		if (errors.size() > 0)
			return actionForward;

		session.setAttribute(this.getSessionSimpleSearchStatus(),
				STATUS_CREATE_EXCEL);
		return actionForward;
	}

	private ActionForward processStatusCreatePdf(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) throws Exception {
		
		form.setPageEventSrc(ACTION_CREATE_TXT);
		GenericPdfGenerator pdfGenerator = new GenericPdfGenerator(form);
		pdfGenerator.generate(mapping, request, response, servlet, errors);

		return null;
	}

	private ActionForward processStatusCreateHtmlTxt(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) throws Exception {
		form.setPageEventSrc(ACTION_CREATE_HTML_TXT);
		GenericInquiryTxtGenerator txtGen = new GenericInquiryTxtGenerator(form);
		txtGen.generate(mapping, request, response, servlet, errors);
		return null;
	}
	
	private ActionForward processStatusCreateTxt(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) throws Exception {
		GenericInquiryTxtGenerator txtGen = new GenericInquiryTxtGenerator(form);
		txtGen.generate(mapping, request, response, servlet, errors);

		return null;
	}

	private ActionForward processStatusCreateExcel(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) throws Exception {
		System.out.println(form);
		GenericExcelGenerator excelGenerator = new GenericExcelGenerator(form);
		excelGenerator.generate(mapping, request, response, servlet, errors);

		return null;
	}

	private void processActionPopupSearch(GenericInquirySearchForm form,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors) {
		HttpSession session = request.getSession(false);
		User editingUser = (User) session.getAttribute(SimpleConstants.SESSION_USER);
		String eventSrc = form.getPageEventSrc();
		//ChildList list = form.getGenericInquiryMasterVO().getChilds(InquiryCriteriaVO.class, editingUser.getUserId());
        ChildList list = form.getGenericInquiryMasterVO().getChilds(InquiryCriteriaVO.class);
		InquiryCriteriaVO vo = (InquiryCriteriaVO)list.get(Integer.parseInt(eventSrc));
		PopupSearchTemplateComponent comp;
		
		try {
			comp = new PopupSearchTemplateComponent(vo.getFieldCode(), session,
					getSessionSimpleSearchStatus(), STATUS_POPUP_SEARCH, 
					getFunctionId());
			if (!vo.getFieldType().equals(GenericInquiryConstants.FIELD_TYPE_POPUP_SELECT_MULTIPLE))
				comp.setExclusive(true);
			
			comp.setEventSrc(eventSrc);

			PopupSearchTemplateFactory factory = PopupSearchTemplateFactory.create(vo.getFieldCode());
			factory.execute(comp);

			if(vo.getFieldType().equalsIgnoreCase("MOD_INQ_COSTING_RPT_NEW_FORMAT")||
					vo.getFieldCode().equalsIgnoreCase("projNo")){
				HashMap params = (HashMap)session.getAttribute(ProjectConstants.SESSION_COMMON_SEARCH_PARAMETERS);
				LinkedList criteriaList = new LinkedList();
		        ArrayList criteriaColumnList = new ArrayList();
		        ArrayList rsltTextList = new ArrayList();
		        ArrayList rsltColumnList = new ArrayList();
		        Hashtable tblParams = new Hashtable();
		        criteriaList.add("Project No.");
				criteriaList.add("INPUT_WITH_WILDCARD");
				criteriaList.add("");		
				criteriaColumnList.add("PROJ_NO");
				rsltTextList.add("Project No.");
				rsltTextList.add("Description");
				rsltColumnList.add("PROJ_NO");
				rsltColumnList.add("DESCRIPTION");
				
				String table = "T_PROJ_HDR";
		        String whereClause = " COMPANY_CODE ='"+WebUtil.getAppropriateCompanyCode(session, null)+"'";
		        tblParams.put(ProjectConstants.SESSION_TABLE, table);
		        tblParams.put(ProjectConstants.SESSION_WHERE, whereClause);
		        tblParams.put(ProjectConstants.SESSION_ORDERBY, "PROJ_NO");
		        params.put(ProjectConstants.SESSION_CRITERIA_LIST, criteriaList);
				params.put(ProjectConstants.SESSION_CRITERIA_COLUMN_LIST, criteriaColumnList);
				params.put(ProjectConstants.SESSION_RESULT_TEXT_LIST, rsltTextList);
				params.put(ProjectConstants.SESSION_RESULT_COLUMN_LIST, rsltColumnList);
				params.put(ProjectConstants.SESSION_TABLE_PARAMS, tblParams);
			}
			
		} catch (InvalidComponentArgumentException e) {
			Logger.logExceptions(e);
		}
	}

	protected ActionForward processStatus(ActionMapping mapping,
			ActionForm formIn, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors, String rb_status) {
		HttpSession session = request.getSession(false);
		GenericInquirySearchForm form = (GenericInquirySearchForm) formIn;

		ActionForward actionForward = new ActionForward(mapping.getInput());

		if (STATUS_POPUP_SEARCH.equalsIgnoreCase(rb_status)) {
			processStatusPopupSearch(form, request, response, errors);
		}

		try {
			if (STATUS_CREATE_EXCEL.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreateExcel(mapping, form,
						request, response, errors);
			else if (STATUS_CREATE_PDF.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreatePdf(mapping, form, request,
						response, errors);
			else if (STATUS_CREATE_TXT.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreateTxt(mapping, form, request,
						response, errors);
			else if (STATUS_CREATE_HTML_TXT.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreateHtmlTxt(mapping, form, request,
						response, errors);			
			else if (STATUS_CREATE_EXCEL_HTML.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreateExcelHtml(mapping, form,
						request, response, errors);
			else if (STATUS_CREATE_CSV.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreateCsv(mapping, form, request,
						response, errors);
			else if (STATUS_CREATE_EXCEL_WITH_JAVA.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreateExcelWithJava(mapping, form,
						request, response, errors);
			else if (STATUS_CREATE_EXCEL_HTML_WITH_JAVA
					.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreateExcelHtmlWithJava(mapping,
						form, request, response, errors);
			else if (STATUS_CREATE_CSV_WITH_JAVA.equalsIgnoreCase(rb_status))
				actionForward = processStatusCreateCsvWithJava(mapping, form,
						request, response, errors);
		} catch (Exception e) {
			Logger.logExceptions(e);
			e.printStackTrace();

			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.msg",
					e.getMessage()));
		}

		return actionForward;
	}

	private ActionForward processStatusCreateCsv(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) throws Exception {
		GenericFileGenerator generator = new GenericInquiryCSVGenerator(form);
		generator.generate(mapping, request, response, servlet, errors);

		return null;
	}

	private ActionForward processStatusCreateCsvWithJava(ActionMapping mapping,
			GenericInquirySearchForm form, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) throws Exception {
		GenericFileGenerator generator = new GenericInquiryCSVGenerator(form);
		generator.setUseDynamicClass(true);
		generator.generate(mapping, request, response, servlet, errors);

		return null;
	}

	private ActionForward processStatusCreateExcelWithJava(
			ActionMapping mapping, GenericInquirySearchForm form,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors) throws Exception {
		GenericFileGenerator generator = new GenericExcelGenerator(form);
		generator.setUseDynamicClass(true);
		generator.generate(mapping, request, response, servlet, errors);

		return null;
	}

	private ActionForward processStatusCreateExcelHtmlWithJava(
			ActionMapping mapping, GenericInquirySearchForm form,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors) throws Exception {
		GenericFileGenerator generator = new GenericExcelHtmlGenerator(form);
		generator.setUseDynamicClass(true);
		generator.generate(mapping, request, response, servlet, errors);

		return null;
	}

	private void processStatusPopupSearch(GenericInquirySearchForm form,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors) {
		HttpSession session = request.getSession(false);
		User editingUser = (User) session.getAttribute(SimpleConstants.SESSION_USER);
		HashMap params = (HashMap)session.getAttribute(ProjectConstants.SESSION_COMMON_SEARCH_PARAMETERS);
		session.removeAttribute(ProjectConstants.SESSION_COMMON_SEARCH_PARAMETERS);

		ArrayList selectedList = (ArrayList)params.get(ProjectConstants.SESSION_SELECTED_LIST);
		int eventSrc = Integer.parseInt((String)params.get(ProjectConstants.SESSION_EVENTSRC));

		//InquiryCriteriaVO vo = (InquiryCriteriaVO) form.getGenericInquiryMasterVO().getChilds(InquiryCriteriaVO.class, editingUser.getUserId()).get(eventSrc);
        InquiryCriteriaVO vo = (InquiryCriteriaVO) form.getGenericInquiryMasterVO().getChilds(InquiryCriteriaVO.class).get(eventSrc);
		PopupSearchTemplateFactory factory = PopupSearchTemplateFactory.create(vo.getFieldCode());
		StringBuffer value = new StringBuffer();
		StringBuffer label = new StringBuffer();

		for (int i = 0; selectedList != null && i < selectedList.size(); i++) {
			SearchResultRow sRow = (SearchResultRow) selectedList.get(i);
			if (i > 0) {
				value.append(GenericInquiryConstants.DELIMITER_MULTIPLE_POPUP);
				//label.append(", ");
				label.append("<br>");
			}
			value.append((String) factory.getSearchResultValue(sRow));
			label.append((String) factory.getSearchResultLabel(sRow));
			if(vo.getFieldType().equalsIgnoreCase("MOD_INQ_COSTING_RPT_NEW_FORMAT")||
					vo.getFieldCode().equalsIgnoreCase("projNo")){
				value.append(sRow.getColumn1());
				label.append(sRow.getColumn1());
			}
		}

		form.setSrchFrom(eventSrc, value.toString());
		form.setSrchFromLabel(eventSrc, label.toString());
	}

	protected ActionForward processActionSearch(ActionMapping mapping,
			ActionForm formIn, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors) {
		
		return processActionSearch(mapping, formIn, request, response, errors, ProjectConstants.GENERIC_REPORT_TYPE_PAGE);
	}

	protected ActionForward processActionSearch(ActionMapping mapping,
			ActionForm formIn, HttpServletRequest request,
			HttpServletResponse response, ActionErrors errors, int srchReport) {
		HttpSession session = request.getSession(false);
		GenericInquirySearchForm form = (GenericInquirySearchForm) formIn;
		ActionForward actionForward = new ActionForward(mapping.getInput());
		
		User editingUser = (User) session.getAttribute(SimpleConstants.SESSION_USER);

		form.clearResultList();
		form.setReportResultList(null);

		setSearchResultList(form, ProjectConstants.GENERIC_REPORT_TYPE_PAGE, null);


		form.validate(errors);

		if (errors.size() > 0) {
			return actionForward;
		}

		SimpleSearchMaintStyleDelegate dg = getMasterDelegate(session);
		GenericInquirySearchCriteria crit = (GenericInquirySearchCriteria)setCriteria(mapping, formIn, request, response, errors);
		GenericInquiryMasterVO vo = form.getGenericInquiryMasterVO();
		//ChildList critList = vo.getChilds(InquiryCriteriaVO.class, editingUser.getUserId());
        ChildList critList = vo.getChilds(InquiryCriteriaVO.class);
		//ChildList spList = vo.getChilds(InquirySpVO.class, editingUser.getUserId());
        ChildList spList = vo.getChilds(InquirySpVO.class);
		

		boolean useRefCursor = false;
		
		if (spList.size() > 0) {
			InquirySpVO inquirySpVO = (InquirySpVO) spList.get(0);
			useRefCursor = CommonUtil.nullToString(inquirySpVO.getUseRefCursor()).equals(ProjectConstants.GENERIC_YES);
			crit.setSrchStoreProcName(inquirySpVO.getSpName());
			crit.setUseRefCursor(useRefCursor);
		}

		crit.setGenericInquiryCriteriaList(critList);
        String companyCode = WebUtil.getAppropriateCompanyCode(session, null);
		crit.setSrchCompanyCode(companyCode);
		crit.setSrchInquiryType(vo.getInquiryType());
		crit.setSrchUserCode(editingUser.getUserId());
		crit.setSrchFrom(form.parseSrchFrom());
		crit.setSrchTo(form.parseSrchTo());
		crit.setSrchReport(srchReport);
		crit.setAction(form.getPageEvent());
		crit.setSrchDisableChkBox(form.getSrchDisableChkBox());

		GenericInquiryMasterDelegate md = (GenericInquiryMasterDelegate)getMasterDelegate(session);
		
		try {
			GenericInquiryMasterVO tempVO = md.generate(crit, editingUser.getUserId());
			//vo.storeChilds(tempVO.getChilds(InquiryDisplayVO.class, editingUser.getUserId()));
            vo.storeChilds(tempVO.getChilds(InquiryDisplayVO.class));
			crit.setSrchRptTime(tempVO.getRptTime());
			ChildList displayList = vo.getLocalChilds(InquiryDisplayVO.class);
			crit.setGenericInquiryCriteriaList(displayList);
			ArrayList srchRslt = new ArrayList();

			if (useRefCursor) {
				srchRslt = (ArrayList)tempVO.getLocalChilds(InquiryOutputVO.class);
			} else {
				SimpleBaseVo model = (SimpleBaseVo)getMasterVOClass(formIn).newInstance();
				//PageController pcontrol = new PageController(dg, model, crit);
				//pcontrol.setUserCode(editingUser.getUserId());
				//pcontrol.execute();
				//form.setPageControl(pcontrol);

                srchRslt = (ArrayList) dg.findByCriteria(model, crit);
			}

			//setSearchResultList(form, srchReport, srchRslt);
			if (srchReport != ProjectConstants.GENERIC_REPORT_TYPE_PAGE)
                form.setReportResultList(srchRslt);
            else {
                form.setResultList(srchRslt);
            }
			Logger.sql(this, "report time is: " + tempVO.getRptTime());
            
//            if(form.getResultList() != null){
//                for(int k = 0; k < form.getResultList().size(); k++){
//                    InquiryOutputVO tmpVo = (InquiryOutputVO)form.getResultList().get(k);
//                    if(tmpVo.getFields() != null){
//                        System.out.println("************************ACTION, sizeof form.getResultList().getFields()= " + tmpVo.getFields().size());
//                        
//                    }
//                }
//            }

			form.setFilename(tempVO.getFilename());
		} catch (RemoteException e) {
			Logger.logExceptions(this, e);
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.msg",
					e.getMessage()));
			setSearchResultList(form, srchReport, null);
		} catch (Exception e) {
			Logger.logExceptions(this, e);
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.msg",
					e.getMessage()));
			setSearchResultList(form, srchReport, null);
		}

		return actionForward;
	}

	/**
	 * @param srchReport
	 * @param form
	 */
	private void setSearchResultList(GenericInquirySearchForm form,
			int srchReport, ArrayList result) {
		form.setReportResultList(null);
		form.setResultList(null);

		if (srchReport != ProjectConstants.GENERIC_REPORT_TYPE_PAGE)
			form.setReportResultList(result);
		else {
			form.setResultList(result);
		}

		if (form.getResultList() == null) {
			form.setResultList(new ArrayList());
		}
	}

	protected void setOtherCriteria(ActionMapping mapping, ActionForm formIn,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors, Object criteria) {
		HttpSession session = request.getSession(false);
		GenericInquirySearchForm form = (GenericInquirySearchForm) formIn;
	}

	protected void otherPopulate(ActionMapping mapping, ActionForm formIn,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors) {
		HttpSession session = request.getSession(false);
		GenericInquirySearchForm form = (GenericInquirySearchForm) formIn;

		String[] srchFrom = form.getSrchFrom();
		if (srchFrom == null)
			return;

		String[] cbIdx = request.getParameterValues("cbIdx");
		for (int i = 0; cbIdx != null && i < cbIdx.length; i++) {
			String idx = cbIdx[i];
			String[] cb = request.getParameterValues("cb" + idx);
			String cbValue = "";
			for (int j = 0; cb != null && j < cb.length; j++) {
				cbValue += (CommonUtil.isEmpty(cbValue) ? "" : ",") + cb[j];
			}
			srchFrom[Integer.parseInt(idx)] = cbValue;
		}
	}
	
	private void preprocess(GenericInquirySearchForm form) {
	        form.clearResultList();
	        form.getGenericInquiryMasterVO().removeChilds(InquiryDisplayVO.class);
	}
}


